const createError = require('http-errors'); //
const express = require('express');
const path = require('path');
const fs = require('fs');
const cookieParser = require('cookie-parser'); // 
const logger = require('morgan'); // 实现日志的一些方法
const session = require('express-session');
const RedisStore = require('connect-redis')(session); // 生成RedisStore
const cors = require('cors');

const redisClient = require('./db/redis');
const blogRouter = require('./routes/blog');
const manageRouter = require('./routes/manage');

const ENV = process.env.NODE_ENV;


const app = express();

const sessionStore = new RedisStore({
  client: redisClient
})

var corsOptions = {
    origin: '*',
    credentials: true,
    // maxAge: '1728000'
    //这一项是为了跨域专门设置的
  }

// 解决跨域问题
app.use(cors(corsOptions));
// 使用日志 prod-combinded dev-dev
if (ENV === 'development') {
    app.use(logger('dev'));
} else {
  let fileName = path.join(__dirname, 'logs', 'access.log');
  const writeStream = fs.createWriteStream(fileName, {
      flags: 'a',
  })
  app.use(logger(ENV === 'development' ? 'dev' : 'combined', {
    stream: writeStream, // process.stdout,
  }));
}

// 处理post方法
app.use(express.json());
app.use(express.urlencoded({ extended: false }));

// 解析cookie
app.use(cookieParser());

// 处理session session是服务端的，cokie是客户端的
app.use(session({
    secret: 'SGJHGJHGHJas12312xxasd&q$0', // 这里的密钥是单独的
    // resave : false,
    // saveUninitialized: false, // 是否保存未初始化的
    cookie: {
        path: '/', // 默认配置
        httpOnly: true, // 默认配置
        maxAge: 24*60*60*1000, // 24h 失效时间，不用使用expresie 
        domain: 'http://localhost:5000'
    },
    store: sessionStore // 把session存储在redis中
}))

// 处理静态文件-比如上传的图片
app.use(express.static(path.join(__dirname, 'public')));

// 按照不同的模块进行的分拆，走不同的路由分支
app.use('/api/blog', blogRouter);
app.use('/api/manage', manageRouter);


// catch 404 and forward to error handler
app.use((req, res, next) => {
  next(createError(404));
});

// error handler
app.use((err, req, res, next) => {
  // set locals, only providing error in development
  console.log('err.message', err.message)
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.json({ 
    status: 0, 
    msg: '网络错误请稍后重试', data: err.message 
  });
});

module.exports = app;
